package com.bwf.jdbc3;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Version v1.0
 * @Description: TODO
 * @Author ZHANZHONGXIN
 * @Date 2022/6/2 9:58
 * @Copyright 博为峰
 */
public class ClaDaoImpl implements ClaDao {
    @Override
    public int insert(Cla cla, Connection conn) {
//        Connection conn = DBUtil.getConn();
        //插入班级表
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = conn.prepareStatement("insert into t_class(name,num)values(?,?)");
            preparedStatement.setString(1, cla.getName());
            preparedStatement.setInt(2, cla.getNum());
            int i = preparedStatement.executeUpdate();
            //获取主键值
            PreparedStatement lastInsertId = conn.prepareStatement("select last_insert_id()");
            ResultSet resultSet = lastInsertId.executeQuery();
            int classId = 0;
            while (resultSet.next()) {
                classId = resultSet.getInt(1);
            }
//            int n = 1 / 0;
            return classId;
        } catch (SQLException throwables) {
            throw new RuntimeException("插入班级异常");
        } finally {
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}
